/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package converters;

import bc.Apoderado;
import beans.ManagedBeanApoderado;
import javax.el.ValueExpression;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext; 
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;

/**
 *
 * @author yzavaleta
 */
@FacesConverter(value = "apoderadoConverter")
public class ApoderadoConverter implements Converter {
   @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {

        if (context == null) {
            throw new NullPointerException("context");
         }
        if (component == null) {
            throw new NullPointerException("component");
        }
      FacesContext ctx = FacesContext.getCurrentInstance();
      ValueExpression vex = ctx.getApplication().getExpressionFactory().createValueExpression(ctx.getELContext(),"#{managedBeanApoderado}", ManagedBeanApoderado.class);
      ManagedBeanApoderado managedBean = (ManagedBeanApoderado)vex.getValue(ctx.getELContext());
      Apoderado objeto;
     try {
        if(managedBean.getMyMapItems().size()<1){
        // No se han llenado los Objetos
        // System.out.println(" Mandamos a Llenar los My");
        managedBean.llenar_myItems();
        }
        objeto =  managedBean.getObjeto(new Integer(value));
        } catch( NumberFormatException e ) {
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Valor Desconocido", "Este no es un Tipo Tramite" );
            throw new ConverterException( message );
        }
        if( objeto == null ) {
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR,"Valor Desconocido", "El Tipo tramite desconocida" );
            throw new ConverterException( message );
        }
        return objeto;
}



    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {


    if (context == null){throw new NullPointerException("context");}
        if (component == null){throw new NullPointerException("component");}
            if(value== null ||  ((Apoderado)value).getIdApoderado() ==null){return "";}

            return ((Apoderado)value).getIdApoderado().toString();
    }
   
}
